package com.daisuxia.risk.service;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.daisuxia.back.utils.ServiceResult;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.risk.dao.IRiskCreditUserDao;
import com.daisuxia.risk.pojo.RiskCreditUser;
import com.daisuxia.risk.pojo.RiskOrders;
import com.daisuxia.risk.utils.ConstantRisk;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.p2p.ZzcRequest;
import com.daisuxia.web.util.OrderNoUtil;

/**
 * 中智诚黑名单接口
 * @author zhangsh Tel:13817876783
 * @date 2017年10月18日 上午9:21:23
 * @Title: ZzcService
 * @ClassName: ZzcService
 * @Description:
 */
@Service
public class ZzcService implements IZzcService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private IRiskOrdersService riskOrdersService;
	@Autowired
	private IRiskCreditUserDao riskCreditUserDao;

	@Override
	public ServiceResult getBlack(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			Object userPhone = params.get("userPhone");
			if (userName != null && cardNum != null && userId != null && userPhone != null) {
				LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.ZZC);
				String url = map2.get("ZZC_URL");
				String name = map2.get("ZZC_NAME");
				String pwd = map2.get("ZZC_PWD");
				String jsonStrData = "{\"name\":\"" + userName + "\",\"pid\":\"" + cardNum + "\",\"mobile\":\""
						+ userPhone + "\"}";
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZZC);
				orders.setAct(ConstantRisk.ZZC_BLACK);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams("url=" + url + ",jsonStrData=" + jsonStrData);
				logger.info("zzc1 card" + cardNum);
				riskOrdersService.insert(orders);
				HttpClient c = new HttpClient();
				c.getParams().setContentCharset("utf-8");
				c.getParams().setAuthenticationPreemptive(true);

				Credentials defaultcreds = new UsernamePasswordCredentials(name, pwd);
				c.getState().setCredentials(AuthScope.ANY, defaultcreds);

				PostMethod postMethod = new PostMethod(url);
				// 可根据需要变更查询字段值

				RequestEntity r = new StringRequestEntity(jsonStrData, "application/json", "utf-8");
				postMethod.setRequestEntity(r);
				c.executeMethod(postMethod);

				// 可在此获取返回结果json字符串进行处理
				String result = postMethod.getResponseBodyAsString();
				if (StringUtils.isNotBlank(result)) {
					JSONObject jsonObject = JSONObject.fromObject(result);
					if (jsonObject.containsKey("errors") || jsonObject.containsKey("error")) {
						Object errObject = jsonObject.get("error");
						if (errObject == null) {
							errObject = jsonObject.get("errors");
						}
						serviceResult = new ServiceResult("300", errObject + "");
					} else {
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, result);
						orders.setStatus(RiskOrders.STATUS_SUC);
					}
					orders.setReturnParams(result);
					riskOrdersService.update(orders);
				} else {
					orders.setReturnParams("td return null");
					serviceResult = new ServiceResult("100", "中智诚返回空或请求报错");
				}
				riskOrdersService.update(orders);

			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getRisk error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult getFqz(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userName = params.get("userName");
			Object cardNum = params.get("cardNum");
			Object userId = params.get("userId");
			Object userPhone = params.get("userPhone");
			if (userName != null && cardNum != null && userId != null && userPhone != null) {
				RiskCreditUser riskCreditUser = riskCreditUserDao.findUserDetail(Integer.valueOf(userId + ""));
				// Integer marital_status = riskCreditUser.getMaritalStatus();

				String work_name = StringUtils.isNotBlank(riskCreditUser.getCompanyName())
						? riskCreditUser.getCompanyName() : "";
				String work_phone = StringUtils.isNotBlank(riskCreditUser.getCompanyPhone())
						? riskCreditUser.getCompanyPhone() : "";
				String work_address = StringUtils.isNotBlank(riskCreditUser.getCompanyAddress())
						? riskCreditUser.getCompanyAddress() : "";
				String home_address = StringUtils.isNotBlank(riskCreditUser.getPresentAddress())
						? riskCreditUser.getPresentAddress() : "";
				ZzcRequest zzcRequest = new ZzcRequest();
				zzcRequest.setName(userName.toString());
				zzcRequest.setLoan_type("1");
				zzcRequest.setPid(cardNum.toString());
				zzcRequest.setMobile(userPhone.toString());
				zzcRequest.setHome_address(home_address);
				zzcRequest.setWork_address(work_address);
				zzcRequest.setWork_name(work_name);
				zzcRequest.setWork_phone(work_phone);
				String jsonStrData = JSON.toJSONString(zzcRequest);

				LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.ZZC);
				String url = map2.get("ZZC_URL");
				String name = map2.get("ZZC_NAME");
				String pwd = map2.get("ZZC_PWD");
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZZC);
				orders.setAct(ConstantRisk.ZZC_FQZ_CREATE);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams("url=" + url + ",jsonStrData=" + jsonStrData);
				logger.info("zzc2 card" + cardNum);
				riskOrdersService.insert(orders);
				HttpClient c = new HttpClient();
				c.getParams().setContentCharset("utf-8");
				c.getParams().setAuthenticationPreemptive(true);

				Credentials defaultcreds = new UsernamePasswordCredentials(name, pwd);
				c.getState().setCredentials(AuthScope.ANY, defaultcreds);

				PostMethod postMethod = new PostMethod(url);
				// 可根据需要变更查询字段值

				RequestEntity r = new StringRequestEntity(jsonStrData, "application/json", "utf-8");
				postMethod.setRequestEntity(r);
				c.executeMethod(postMethod);

				// 可在此获取返回结果json字符串进行处理
				String result = postMethod.getResponseBodyAsString();
				if (StringUtils.isNotBlank(result) && result.length() > 0) {
					com.alibaba.fastjson.JSONObject jsONObject=  JSON.parseObject(result);
					if(jsONObject.containsKey("errorCode")){
						serviceResult = new ServiceResult("400", result);
						orders.setStatus(RiskOrders.STATUS_OTHER);
						logger.info("call zzc request error errorCode: "+jsONObject.get("errorCode")+",  response "+result);
					}else{
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, result);
						orders.setStatus(RiskOrders.STATUS_SUC);
					}
					
					

					orders.setReturnParams(result);
					riskOrdersService.update(orders);
				} else {
					orders.setReturnParams("getFqz return null");
					serviceResult = new ServiceResult("100", "中智诚返回空或请求报错");
				}
				riskOrdersService.update(orders);

			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("getFqz error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult findFqz(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			Object userId = params.get("userId");
			Object zzcId = params.get("zzcId");
//			if (userId != null && zzcId != null) {
			if (userId != null) {
				LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.ZZC);
				String url = map2.get("ZZC_URL");
				String name = map2.get("ZZC_NAME");
				String pwd = map2.get("ZZC_PWD");
//				url = url.replaceAll("\\{id\\}", zzcId + "");
				RiskOrders orders = new RiskOrders();
				orders.setUserId(userId + "");
				orders.setOrderType(ConstantRisk.ZZC);
				orders.setAct(ConstantRisk.ZZC_FQZ_REPORT);
				orders.setOrderNo(OrderNoUtil.getInstance().getUUID());
				orders.setReqParams("url=" + url);
				logger.info("zzc3 userId" + userId);
				riskOrdersService.insert(orders);
				HttpClient c = new HttpClient();
				c.getParams().setContentCharset("utf-8");
				c.getParams().setAuthenticationPreemptive(true);

				Credentials defaultcreds = new UsernamePasswordCredentials(name, pwd);
				c.getState().setCredentials(AuthScope.ANY, defaultcreds);

				GetMethod getMethod = new GetMethod(url);
				// 可根据需要变更查询字段值
				c.executeMethod(getMethod);

				// 可在此获取返回结果json字符串进行处理
				String result = getMethod.getResponseBodyAsString();
				if (StringUtils.isNotBlank(result)) {
					JSONObject jsonObject = JSONObject.fromObject(result);
					if (jsonObject.containsKey("errors") || jsonObject.containsKey("error")) {
						Object errObject = jsonObject.get("error");
						if (errObject == null) {
							errObject = jsonObject.get("errors");
						}
						serviceResult = new ServiceResult("300", errObject + "");
					} else {
						serviceResult = new ServiceResult(ServiceResult.SUCCESS, result);
						orders.setStatus(RiskOrders.STATUS_SUC);
					}
					orders.setReturnParams(result);
					riskOrdersService.update(orders);
				} else {
					orders.setReturnParams("findFqz return null");
					serviceResult = new ServiceResult("100", "中智诚返回空或请求报错");
				}
				riskOrdersService.update(orders);

			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}
		} catch (Exception e) {
			logger.error("findFqz error ,params=" + params, e);
		}
		return serviceResult;
	}

	@Override
	public ServiceResult setBlack(HashMap<String, Object> params) {
		ServiceResult serviceResult = new ServiceResult("500", "未知异常，请稍后重试！");
		try {
			// 测试环境
			// String url =
			// "https://test.intellicredit.cn/blacklist/api/v2/blacklist";
			// String name = "18643515288@163.com";
			// String pwd = "RIyikeji888";

			String name1 = params.get("realName") + "";
			String phone1 = params.get("userPhone") + "";
			String pid = params.get("idNumber") + "";
			String applied_at = params.get("applied_at") + "";
			String confirmed_at = params.get("confirmed_at") + "";

			String name2 = params.get("firstContactName") + "";
			String phone2 = params.get("firstContactPhone") + "";

			LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.ZZC);
			String url = map2.get("ZZC_URL_BLACK");
			String name = map2.get("ZZC_NAME");
			String pwd = map2.get("ZZC_PWD");

			String contacts = "[{\"name\":\"" + name2 + "\",\"phone\":\"" + phone2 + "\"}]";
			String jsonStrData = "{\"loan_type\":\"2\",\"confirm_type\":\"overdue\",\"name\":\"" + name1 + "\","
					+ "\"pid\":\"" + pid + "\"," + "\"applied_at\":\"" + applied_at + "\",\"confirm_details\":\"M1\","
					+ "\"confirmed_at\":\"" + confirmed_at + "\",\"mobile\":\"" + phone1 + "\",\"contacts\":" + contacts
					+ "}";
			System.err.println(jsonStrData.toString());
			HttpClient c = new HttpClient();
			c.getParams().setContentCharset("utf-8");
			c.getParams().setAuthenticationPreemptive(true);

			Credentials defaultcreds = new UsernamePasswordCredentials(name, pwd);
			c.getState().setCredentials(AuthScope.ANY, defaultcreds);
			PostMethod postMethod = new PostMethod(url);
			// 可根据需要变更查询字段值
			RequestEntity r = new StringRequestEntity(jsonStrData, "application/json", "utf-8");
			postMethod.setRequestEntity(r);
			c.executeMethod(postMethod);
			// 可在此获取返回结果json字符串进行处理
			String result = postMethod.getResponseBodyAsString();
			JSONObject jsonObject = JSONObject.fromObject(result);
			if (jsonObject.containsKey("uuid")) {
				serviceResult = new ServiceResult(ServiceResult.SUCCESS, "提交中智诚黑名单成功！");
			} else {
				serviceResult = new ServiceResult("400", "必要参数不足！");
			}

			logger.info("+=============================+" + result.toString());

		} catch (IOException e) {

			logger.error("setblack error ", e);
		}

		return serviceResult;
	}

}
